/**
 * 
 */
package org.xelnaga.defiler.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import nl.captcha.Captcha;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xelnaga.defiler.domain.UserModel;
import org.xelnaga.defiler.security.SpringSecurityContext;
import org.xelnaga.defiler.service.UserService;

/**
 * @author qijb
 *
 */
@Controller
@RequestMapping("/register/")
public class RegisterController {
	@Autowired
	private UserService userService;

	/**
	 * 
	 */
	public RegisterController() {
		// TODO Auto-generated constructor stub
	}
	@RequestMapping(value = "new")
	public String register(Model model) {
		model.addAttribute("user", new UserModel());
		return "page/register/new";
	}
	
	@RequestMapping(value = "checkNick")
	@ResponseBody
	public RegisterCheckMessage<String> checkNick(HttpServletRequest request) {
		RegisterCheckMessage<String> message = new RegisterCheckMessage<String>();
		message.setSuccess(true);
		String nick = request.getParameter("nick");
		if(StringUtils.isNotBlank(nick)) {
			UserModel user = userService.getByLoginName(nick);
			if(null != user) {
				message.setSuccess(false);
				message.setReason("ERROR_DUP_NICK_NAME");
			}
		}
		return message;
	}
	
	@RequestMapping(value = "checkPassword")
	@ResponseBody
	public RegisterCheckMessage<String> checkPassword(HttpServletRequest request) {
		RegisterCheckMessage<String> message = new RegisterCheckMessage<String>();
		message.setSuccess(true);
		return message;
	}
	
	@RequestMapping(value = "checkEmail")
	@ResponseBody
	public RegisterCheckMessage<String> checkEmail(HttpServletRequest request) {
		RegisterCheckMessage<String> message = new RegisterCheckMessage<String>();
		message.setSuccess(true);
		String email = request.getParameter("email");
		if(StringUtils.isNotBlank(email)) {
			UserModel user = userService.getByEmail(email);
			if(null != user) {
				message.setSuccess(false);
				message.setReason("ERROR_DUP_EMAIL");
			}
		}
		return message;
	}
	
	@RequestMapping(value = "checkcode")
	@ResponseBody
	public RegisterCheckMessage<String> checkcode(HttpServletRequest request) {
		RegisterCheckMessage<String> message = new RegisterCheckMessage<String>();
		message.setSuccess(true);
		return message;
	}
	
	@RequestMapping(value = "done")
	public String registerNew(@ModelAttribute UserModel user, BindingResult result, HttpServletRequest request) {
		user.initDefaultValues();
		Captcha captcha = (Captcha)request.getSession().getAttribute(Captcha.NAME);
		Map<String, String> messagesMap = new HashMap<String, String>();
		if(null == captcha) {//No captch
			result.rejectValue("middleName", "register.user.code.empty", "请输入验证码。");
			messagesMap.put("middleName", "请输入验证码。");
		} else {
			if(!StringUtils.equalsIgnoreCase(user.getMiddleName(), captcha.getAnswer())) {
				result.rejectValue("middleName", "register.user.code.error", "请正确输入验证码。");
				messagesMap.put("middleName", "请正确输入验证码。");
			}
		}
		if(!StringUtils.equals(user.getPassword_(), user.getNickName())) {
			result.rejectValue("password_", "register.user.password_.notequal", "登录密码与再次输入密码不一致。");
			messagesMap.put("password_", "登录密码与再次输入密码不一致。");
		}
		UserModel oldUser = userService.getByLoginName(user.getLoginName());
		if(null != oldUser) {
			result.rejectValue("loginName", "register.user.loginName.used", "会员名：" + user.getLoginName() + " 已被使用。");
			messagesMap.put("loginName", "会员名：" + user.getLoginName() + " 已被使用。");
		}
		oldUser = userService.getByEmail(user.getEmail());
		if(null != oldUser) {
			result.rejectValue("email", "register.user.email.used", "电子邮件地址：" + user.getEmail() + " 已被使用。");
			messagesMap.put("email", "电子邮件地址：" + user.getEmail() + " 已被使用。");
		}
		
		if(result.hasErrors()) {
			request.setAttribute("user", user);
			request.setAttribute("messagesMap", messagesMap);
			return "page/register/new";
		}
		try {
			userService.save(user);
			
			SpringSecurityContext.forceAuthentication(user.getLoginName(), 
					user.getPassword_(), new UserModel().getRoleNames());
		}catch (Exception e) {
			return "page/register/new";
		}
		return "redirect:/user/index";
	}

}
